package cn.tedu.egmvc4.controller;

import cn.tedu.egmvc4.base.response.JsonResult;
import cn.tedu.egmvc4.base.response.StatusCode;
import cn.tedu.egmvc4.mapper.UserMapper;
import cn.tedu.egmvc4.pojo.dto.UserAddParam;
import cn.tedu.egmvc4.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc4.pojo.entity.User;
import cn.tedu.egmvc4.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Api(tags="01.用户管理模块")
public class UserController {
    @Autowired private UserMapper userMapper;
    @PostMapping("add")
    @ApiOperation(value="添加用户")
    @ApiOperationSupport(order=10)
    public JsonResult add(UserAddParam userAddParam){
        log.debug("userAddParam="+userAddParam);
        User user=new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int num= userMapper.insertUser(user);
        if(num>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
    @GetMapping("list")
    @ApiOperation(value="用户列表")
    @ApiOperationSupport(order=20)
    public JsonResult list(){
        List<UserListVO> userListVOs=userMapper.list();
        return JsonResult.ok(userListVOs);
    }
    @PostMapping("del")
    @ApiOperation(value="删除用户")
    @ApiOperationSupport(order=30)
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    public JsonResult del(Long id){
        if(id<0){
            throw new IllegalArgumentException("id值非法");
        }
        int num = userMapper.delete(id);
        if(num>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
    @PostMapping("update")
    @ApiOperation(value="修改用户")
    @ApiOperationSupport(order=40)
    public JsonResult update(@ApiIgnore UserUpdateParam userUpdateParam){
        log.debug("userUpdateParam="+userUpdateParam);
        User user=new User();
        BeanUtils.copyProperties(userUpdateParam,user);
        user.setUpdateTime(new Date());
        int num = userMapper.update(user);
        if(num>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
}
